package com.jiang.jetpackdemo.fragment

import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jiang.jetpackdemo.database.NewsInfoDao
import com.jiang.jetpackdemo.database.RoomHelper
import com.jiang.jetpackdemo.model.NewsInfo
import com.jiang.jetpackdemo.utils.SPUtil
import com.jiang.jetpackdemo.utils.WebCrawler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


class NewsRecommendViewModel : ViewModel() {
    private val newsList: MutableLiveData<MutableList<NewsInfo>> = MutableLiveData()
    private val sizeOfNewsList: MutableLiveData<Int> = MutableLiveData()
    private lateinit var roomHelper: RoomHelper
    private lateinit var dao: NewsInfoDao
    private lateinit var spUtil: SPUtil

    init {
        newsList.value = ArrayList()
        sizeChange()
    }

    private fun sizeChange() {
        sizeOfNewsList.value = newsList.value?.size
    }

    fun getNewsList(): MutableList<NewsInfo> = newsList.value!!
    fun getSizeOfNewsList() = sizeOfNewsList
    private fun resetVideoInfoList(list: MutableList<NewsInfo>) {
        newsList.value?.clear()
        newsList.value?.addAll(list)
        sizeChange()
    }

    fun initTool(context: Context) {
        roomHelper = RoomHelper(context)
        dao = roomHelper.getNewsInfoDao()
        spUtil = SPUtil(context)
    }

    fun closeDb() {
        roomHelper.closeDb()
    }

    fun getData() {
        try {
            GlobalScope.launch(Dispatchers.Main) {
                if (spUtil.isOutOfDate(SPUtil.KEY_NEWS_DATE) || !getDataFromLocal()) getDataFromNet()
            }
        } catch (e: Exception) {
            Log.e("getData", "${e.message}", e)
        }

    }

    private fun getDataFromLocal(): Boolean {
        val queryAll = dao.queryAll()
        return if (queryAll.isNullOrEmpty()) {
            false
        } else {
            resetVideoInfoList(queryAll)
            Log.d("getDataFromLocal", "$queryAll")
            true
        }
    }

    suspend fun getDataFromNet() {
        val newsInfos = WebCrawler.getNewsInfo()
        if (newsInfos.isNotEmpty()) {
            resetVideoInfoList(newsInfos)
            dao.insertAll(newsInfos)
            spUtil.setNewsCacheDate()
        }
    }
}
